import React from "react";
import styles from "./todo-list.module.css";
import TodoListItem from "./components/TodoListItem";
import Popup from "./components/Popup";
import { CSSTransition, TransitionGroup } from "react-transition-group";
import BaseButton from "./components/BaseButton";
import DrawMenu from "../drawMenu";
import store from "../../store/index";
import {
  addTodoListItem,
  deleteTodoListItem,
} from "../../store/actionCreator.js";

class TodoList extends React.Component {
  constructor(props) {
    super(props);
    this.positions = [];
    this.state = {
      todoListData: [],
      isShowPopup: false,
      isOpenMenu: false,
    };
    store.subscribe(() => {
      console.log(store.getState());
    });
  }
  componentDidUpdate() {
    localStorage.setItem(
      "todoListData",
      JSON.stringify(this.state.todoListData)
    );
  }
  componentDidMount() {
    let todoListData = localStorage.getItem("todoListData");
    todoListData = (todoListData && JSON.parse(todoListData)) || [];
    this.setState({
      todoListData: [...todoListData],
    });
    this.addInput.focus();
  }
  handleAddTodoListClick = (event) => {
    event.preventDefault();
    const input = this.addInput;
    const addTarget = {
      id: Date.now(),
      text: input.value,
      isComplete: false,
      content: "",
    };
    store.dispatch(addTodoListItem(addTarget));
    this.setState(
      (preState) => {
        const todoListData = [...preState.todoListData, addTarget];
        return {
          todoListData,
        };
      },
      () => {
        input.value = "";
      }
    );
  };
  handleChangeComplate = (data) => {
    const todoListData = this.state.todoListData.map((listItem) => {
      if (listItem.id === data.id) listItem.isComplete = !data.isComplete;
      return listItem;
    });
    this.setState({
      todoListData,
    });
  };
  handleDeleteItem = (data) => {
    this.setState((prevState) => ({
      isShowPopup: !prevState.isShowPopup,
    }));
    this.isShowPopup = true;
    this.currentId = data.id;
  };
  handleSureDeleteClick = () => {
    this.setState(() => ({
      isShowPopup: false,
    }));
    store.dispatch(deleteTodoListItem(this.currentId));
    // 可以浅拷贝，再用splice
    const todoListData = this.state.todoListData.filter(
      (data) => data.id !== this.currentId
    );
    this.setState({
      todoListData,
    });
  };
  handleNotDeleteClick = () => {
    this.setState(() => ({
      isShowPopup: false,
    }));
  };
  getTodoItemPosition = (position) => {
    this.positions.push(position);
  };
  handleDragStart = (index) => {
    this.dragIndex = index;
  };
  handleDrop = (index) => {
    if (index !== this.dragIndex) {
      let todoListData = [...this.state.todoListData];
      const template = todoListData[index];
      todoListData[index] = todoListData[this.dragIndex];
      todoListData[this.dragIndex] = template;
      this.setState({
        todoListData,
      });
    }
  };
  handleTodoListItemClick = (index) => {
    this.setState({
      isOpenMenu: true,
    });
    this.currentList = this.state.todoListData[index];
  };
  handleCloseRightMenu = () => {
    this.setState({
      isOpenMenu: false,
    });
  };
  render() {
    const { todoListData, isOpenMenu } = this.state;
    return (
      <div className={styles["container"]}>
        <h3>TODO LIST</h3>
        <form>
          <div className={styles["addlist-add-wrap"]}>
            <input
              type="text"
              placeholder="please input todo name"
              ref={(addInput) => (this.addInput = addInput)}
            ></input>
            <BaseButton
              onClick={this.handleAddTodoListClick}
              className={styles["add-button"]}
            >
              add
            </BaseButton>
          </div>
          <TransitionGroup className={styles["todo-list-content"]}>
            {todoListData.map((listItem, index) => {
              return (
                <CSSTransition
                  timeout={300}
                  key={listItem.id}
                  classNames={"fade"}
                >
                  <TodoListItem
                    {...listItem}
                    index={index}
                    handleChangeComplate={this.handleChangeComplate}
                    handleDeleteItem={this.handleDeleteItem}
                    getTodoItemPosition={this.getTodoItemPosition}
                    handleDragStart={this.handleDragStart}
                    handleDrop={this.handleDrop}
                    handleTodoListItemClick={this.handleTodoListItemClick}
                  ></TodoListItem>
                </CSSTransition>
              );
            })}
          </TransitionGroup>
        </form>
        <CSSTransition
          timeout={300}
          classNames="fade"
          in={this.state.isShowPopup}
          unmountOnExit={true}
          appear
          onEnter={() => console.log("进入动画执行之前")}
        >
          <Popup
            handleSureDeleteClick={this.handleSureDeleteClick}
            handleNotDeleteClick={this.handleNotDeleteClick}
            isShowPopup={this.state.isShowPopup}
            title={<h3>你确定要删除吗?</h3>}
          />
        </CSSTransition>
        <DrawMenu
          isOpen={isOpenMenu}
          handleCloseRightMenu={this.handleCloseRightMenu}
          title={
            <div>
              <h3 style={{ marginTop: "5px", color: "brown" }}>
                {this.currentList?.text}
              </h3>
            </div>
          }
          style={{
            backgroundColor: this.currentList?.isComplete
              ? "orange"
              : "skyblue",
          }}
        >
          <div className={styles["menu-content"]}>
            <div className={styles["menu-textarea"]}>
              <textarea
                defaultValue={this.currentList?.content}
                ref={(textarea) => (this.textarea = textarea)}
                key={Date.now()}
              ></textarea>
            </div>
            <div className={styles["other-content"]}></div>
            <div className={styles["menu-footer"]}>
              <button
                onClick={() => {
                  const value = this.textarea.value;
                  const todoListData = this.state.todoListData.map((item) => {
                    if (item.id === this.currentList?.id) {
                      item.content = value;
                    }
                    return item;
                  });
                  this.setState({
                    todoListData,
                    isOpenMenu: false,
                  });
                }}
              >
                保存
              </button>
              <button
                onClick={() => {
                  this.forceUpdate();
                }}
              >
                重置
              </button>
            </div>
          </div>
        </DrawMenu>
      </div>
    );
  }
}
export default TodoList;
